import { Button, InputNumber, message, Radio, RadioChangeEvent } from "antd"
import { useEffect, useRef, useState } from "react"
import HomePage_CardTitleComponent from "../../../../component/cardtitle"
import HomePage_DateTimePickerComponent from "../../../../component/dateTimePicker"
import HomePage_ModalComponent from "../../../../component/modal"
import lessModule from "./index.module.less"
import HomePage_SingleBtnComponent from "../../../../component/singleBtn"
import HomePage_MultipleBtnComponent from "../../../../component/multipleBtn"
import { $EventBus_off, $EventBus_on } from "../../../../../../common/utils"
import { $Http } from "../../../../../../network"
import dayjs from 'dayjs';

// 主页-默认配置页面
const HomePage_SystemSettingsPage_DefaultConfigurationPage = () => {
    let [groupData, setGourpData] = useState<object>({})
    const [defaultData, setDefaultData] = useState<object>({})
    const [time, setTime] = useState<string>("")
    const dateTimeIntervalRef = useRef<NodeJS.Timeout | null>(null);
    const groupList = [
        {
            title: "系统默认显示",
            children: [
                {
                    label: "单主变",
                    key: "singleMonitor",
                    type: "singleBtn",
                    monitoringType: "主变",
                    monitorModalName: "选择监测主变",
                },
                {
                    label: "多主变",
                    key: "multipleMonitor",
                    type: "multipleBtn",
                    monitoringType: "主变",
                    monitorModalName: "选择监测主变",
                },
                {
                    label: "单线路",
                    key: "singleLine",
                    type: "singleBtn",
                    monitoringType: "线路",
                    monitorModalName: "选择监测线路",
                },
                {
                    label: "多线路",
                    key: "multipleLine",
                    type: "multipleBtn",
                    monitoringType: "线路",
                    monitorModalName: "选择监测线路",
                },
            ]
        },
        {
            title: "其他设置",
            children: [
                {
                    label: "服务器时间",
                    key: "服务器时间",
                    type: "cogradient"
                },
                {
                    label: "装置采集率",
                    key: "collectionRates",
                    type: "inputNumber"
                },
                {
                    label: "是否接受录波文件",
                    key: "isGetFile",
                    type: "radio"
                }
            ]
        }
    ]
    const change_inputNumber: any = (value: number) => {
        groupData["collectionRates"] = value
        setGourpData({ ...groupData })
    }
    const change_radio = (e: RadioChangeEvent) => {
        groupData["isGetFile"] = e.target.value
        setGourpData({ ...groupData })
    };
    const http_search = () => {
        $Http("search", { typeName: "系统设置/默认配置" }).then((res) => {
            groupData = res["data"]
            setGourpData({ ...groupData })
            defaultData["singleMonitor"] = res["data"]["singleMonitorName"]
            defaultData["multipleMonitor"]= res["data"]["multipleMonitorName"]
            defaultData["singleLine"]= res["data"]["singleLineName"]
            defaultData["multipleLine"]= res["data"]["multipleLineName"]
            setDefaultData({ ...defaultData })
        })
    }

    const change_dateTime = () => {
        setTime(dayjs().format("YYYY-MM-DD HH:mm:ss"))
    }
    const change_newDateTime = () => {
        change_dateTime()
        dateTimeIntervalRef.current = setInterval(() => {
            change_dateTime()
        }, 1000)
    }
    const clear_interval = () => {
        dateTimeIntervalRef.current && clearInterval(dateTimeIntervalRef.current)
    }
    const click_time = () => {
        $Http("syncTime", { time }).then((res) => {
            message.success(res["success"])
        })
    }
    // 广播函数数据
    const eventBusFuncData = {

        selectMonitorModalSelectedList: (data: object) => {
            const selectedData = data["data"]
            if (selectedData["selectedList"].length) {
                switch (selectedData["mode"]) {
                    case "single":
                        if ("monitorMain" in selectedData["selectedOtherList"][0]) {
                            defaultData["singleMonitor"] = selectedData["selectedList"][0]
                            groupData["singleMonitor"] = selectedData["selectedOtherList"].map((item: object) => item["deviceID"])
                        }
                        else if ("line" in selectedData["selectedOtherList"][0]) {
                            defaultData["singleLine"] = selectedData["selectedList"][0]
                            groupData["singleLine"] = selectedData["selectedOtherList"].map((item: object) => item["deviceID"])
                        }
                        break;
                    case "multiple":
                        if ("monitorMain" in selectedData["selectedOtherList"][0]) {
                            defaultData["multipleMonitor"] = selectedData["selectedList"]
                            groupData["multipleMonitor"] = selectedData["selectedOtherList"].map((item: object) => item["deviceID"])
                        }
                        else if ("line" in selectedData["selectedOtherList"][0]) {
                            defaultData["multipleLine"] = selectedData["selectedList"]
                            groupData["multipleLine"] = selectedData["selectedOtherList"].map((item: object) => item["deviceID"])
                        }

                        break;
                }
                setDefaultData({ ...defaultData })
            }
        },
        headerOperationSave: (data: object) => {
            $Http("create", { typeName: "系统设置/默认配置", ...groupData }).then((res) => {
                message.success(res["success"])
            })
        }
    }


    useEffect(() => {
        http_search()
        $EventBus_on(eventBusFuncData)
        change_newDateTime()
        return () => {
            clear_interval()
            $EventBus_off(eventBusFuncData)
        }
    }, [])
    return (
        <div className={lessModule["homePageDefaultConfigurationPage"]}>
            {
                groupList.map((item, idx) => (
                    <div key={`group${idx}`} className={lessModule["homePageDefaultConfigurationPage-group"]}>
                        <HomePage_CardTitleComponent title={item["title"]} />
                        {
                            item["children"].map((item, idx) => (
                                <div key={`children${idx}`} className={lessModule["homePageDefaultConfigurationPage-group__row"]} style={{ marginTop: idx ? 24 : 30 }}>
                                    <span>{item["label"]}：</span>
                                    {
                                        item["type"] === "singleBtn" &&
                                        <HomePage_SingleBtnComponent selectedValue={defaultData[item["key"]]} minWidth={180} operation="监测" monitoringType={item["monitoringType"]} monitorModalName={item["monitorModalName"]} />
                                    }
                                    {
                                        item["type"] === "multipleBtn" && <HomePage_MultipleBtnComponent minWidth={180} operation="监测" selectedList={defaultData[item["key"]]} monitoringType={item["monitoringType"]} monitorModalName={item["monitorModalName"]} />
                                    }
                                    {
                                        item["type"] === "cogradient" && <>
                                            <span>{time}</span>
                                            <Button onClick={click_time}>同步</Button>
                                        </>
                                    }
                                    {
                                        item["type"] === "inputNumber" && <>
                                            <InputNumber value={groupData["collectionRates"]} onChange={change_inputNumber} />
                                        </>
                                    }
                                    {
                                        item["type"] === "radio" && <>
                                            <Radio.Group onChange={change_radio} value={groupData["isGetFile"]}>
                                                <Radio value={"是"}>是</Radio>
                                                <Radio value={"否"}>否</Radio>
                                            </Radio.Group>
                                        </>
                                    }
                                </div>
                            ))
                        }
                    </div>
                ))
            }
        </div>
    )
}
export default HomePage_SystemSettingsPage_DefaultConfigurationPage